package DBTool;

import java.sql.*;

public class DB {
    private static final String URL = "jdbc:mysql:///carinfo?useSSL=false&characterEncoding=utf-8";
    private static final String USER = "root";
    private static final String PSW = "root";

    //加载驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("驱动加载异常");
        }
    }

    //获取连接
    public static Connection getconn() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USER, PSW);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    //获取数据库信息
    public static ResultSet query(String sql, Object... keys) {
        Connection conn = getconn();
        ResultSet rs = null;
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i + 1), keys[i]);
            }
            rs = pst.executeQuery();
        } catch (SQLException e) {
            System.out.println("获取数据库数据失败");
        }
        return rs;
    }

    //修改数据库数据
    public static int update(String sql, Object... keys) {
        Connection conn = getconn();
        int num = 0;
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i + 1), keys[i]);
            }
            num = pst.executeUpdate();
        } catch (SQLException e) {
            System.out.println("修改失败");
        }
        return num;
    }
}
